default_encoding = 'utf-8'
# coding: utf-8
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from rest_framework.decorators import api_view
from django.db.models import Q, F
from myblog.models import MamahaoUser
from myblog.mamahaoService.baseCode import getResonCode
from django.core import serializers
import logging
import json
logger = logging.getLogger('log')
import re
import hashlib, time


@csrf_exempt  # 允许跨域访问
@api_view(['POST'])
def adduserPresonnel(request):
    """
    :param request:
    :return:新增修改用户
    """
    data = json.loads(request.body)
    try:
        password = hashlib.md5(bytes(data["password"] + 'mamahaotest', encoding='utf8')).hexdigest()
        response = getResonCode().getSuccess()
        if data["id"] == "":
            myuser = MamahaoUser.objects.filter(user_name=data["name"])
            if list(myuser) != []:
                response = getResonCode().getFail()
                response["msg"] = "已经存在当前用户登录名称"
            else:
                MamahaoUser(user_name=data["name"], user_account=data["user_account"], user_password=password,
                            user_type=data["user_type"]).save()
        else:
            userlist = MamahaoUser.objects.get(user_id=data["id"])
            userlist.user_name = data["name"]
            userlist.user_account = data["user_account"]
            userlist.user_password = password
            userlist.user_type = data["user_type"]
            userlist.save()
            response["msg"] = "修改成功"
        return JsonResponse(response)
    except Exception as e:
        logger.error(e)
        response = getResonCode().getFail()
        response["msg"] = "添加失败，请联系管理员"
        return JsonResponse(response)


@csrf_exempt  # 允许跨域访问
@api_view(['POST'])
def getPresonnel(request):
    data = json.loads(request.body)
    try:
        user = MamahaoUser.objects.filter(user_id=data["id"])
        data = json.loads(serializers.serialize("json", user))
        response = getResonCode().getSuccess()
        response["data"] = data
        return JsonResponse(response)
    except Exception as e:
        logger.error(e)


@csrf_exempt  # 允许跨域访问
@api_view(['POST'])
def getALLPresonnel(request):
    try:
        mamahaoueser = MamahaoUser.objects.all()
        data = json.loads(serializers.serialize("json", mamahaoueser))
        for i in range(len(data)):
            updata_time = data[i]["fields"]["updata_time"]
            data[i]["fields"]["updata_time"] = re.split('[TZ.]', updata_time)[0] + " " + re.split('[TZ.]', updata_time)[
                1]
            del data[i]["fields"]["user_password"]
            del data[i]["fields"]["token"]
        response = getResonCode().getSuccess()
        response["data"] = data
        return JsonResponse(response)
    except EOFError as e:
        logger.error(e)
        response = getResonCode().getFail()
        return JsonResponse(response)

@csrf_exempt  # 允许跨域访问
@api_view(['POST'])
def delPresonnel(request):
    data = json.loads(request.body)
    try:
        MamahaoUser.objects.get(user_id=data["id"]).delete()
        response = getResonCode().getSuccess()
        response["msg"] = "该用户删除成功"
        return JsonResponse(response)
    except Exception as e:
        logger.error(e)
        response = getResonCode().getFail()
        return JsonResponse(response)
